package com.sina.shop.util;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 *  对 数据绑定提供的工具类
 * created  on 12/05/2017.
 */
public abstract class BindingUtils {


    private BindingUtils() {

    }


    /**
     * 将 errors 的 objectError 和 field 转换为 map 格式为
     * {objectName:[],globalErrors:[],fieldErrors:[]}
     * @param errors not null
     * @param messageSource not null
     * @return not null
     * @see #convertGlobalErrorsToMap(List, MessageSource)
     * @see #convertFieldErrorsToMap(List, MessageSource)
     */
    public static Map<String, Object> convertErrorToMap(Errors errors, MessageSource messageSource) {

        Map<String, Object> map = new HashMap<>(5);

        map.put("objectName", errors.getObjectName());
        map.put("globalErrors", convertGlobalErrorsToMap(errors.getGlobalErrors(), messageSource));
        map.put("fieldErrors", convertFieldErrorsToMap(errors.getFieldErrors(), messageSource));

        return map;
    }

    /**
     * 将 FieldError field 为 key ,message 为值创建一个 map
     *
     * @param errors        not null
     * @param messageSource not null
     * @return not null
     */
    public static Map<String, Object> convertFieldErrorsToMap(List<FieldError> errors, MessageSource messageSource) {
        Map<String, Object> globalMap = new HashMap<>((int) (errors.size() / 0.75f));
        Locale locale = LocaleContextHolder.getLocale();

        for (FieldError fieldError : errors) {
            globalMap.put(fieldError.getField(),
                    messageSource.getMessage(fieldError, locale)
            );
        }
        return globalMap;
    }

    /**
     * 将 ObjectErrors 以读出的顺序为 key ,message 为值创建一个 map
     *
     * @param errors        not null
     * @param messageSource not null
     * @return not null
     */
    public static Map<String, Object> convertGlobalErrorsToMap(List<ObjectError> errors, MessageSource messageSource) {
        Map<String, Object> globalMap = new HashMap<>((int) (errors.size() / 0.75f));
        int index = 0;
        Locale locale = LocaleContextHolder.getLocale();

        for (ObjectError objectError : errors) {
            globalMap.put(String.valueOf(index),
                    messageSource.getMessage(objectError, locale)
            );
            index ++;
        }
        return globalMap;
    }




}
